# -*- coding: utf-8 -*-
import xlrd
from pymongo import UpdateOne
from zc_core.client.mongo_client import Mongo
from zc_core.util.batch_gen import time_to_batch_no

from chinagd.rules import *


class CatParser:

    def parse_catalog(self, file):
        cats = list()
        workbook = xlrd.open_workbook(file)
        table = workbook.sheets()[0]
        for row in range(1, table.nrows):
            cat1 = Catalog()
            cat2 = Catalog()
            cat3 = Catalog()

            cat1['catalogId'] = str(int(table.cell_value(row, 2)))
            cat1['catalogName'] = table.cell_value(row, 3)
            cat1['level'] = 1
            self.fill_catalog(cat1)
            cats.append(cat1)

            cat2['catalogId'] = str(int(table.cell_value(row, 4)))
            cat2['catalogName'] = table.cell_value(row, 5)
            cat2['parentId'] = cat1.get('catalogId')
            cat2['level'] = 2
            self.fill_catalog(cat2)
            cats.append(cat2)

            cat3['catalogId'] = str(int(table.cell_value(row, 9)))
            code = table.cell_value(row, 10)
            if code and code != '':
                cat3['catalogCode'] = str(int(code))
            cat3['catalogName'] = table.cell_value(row, 7)
            cat3['parentId'] = cat2.get('catalogId')
            cat3['level'] = 3
            self.fill_catalog(cat3)
            # cat3['typeId'] = str(table.cell_value(rown, 9))
            # cat3['typeCode'] = str(table.cell_value(rown, 10))
            cats.append(cat3)

        return cats

    def fill_catalog(self, catalog):
        if catalog['level'] == 3:
            catalog['leafFlag'] = 1
        else:
            catalog['leafFlag'] = 0
        catalog['linkable'] = 0


if __name__ == '__main__':
    batch_no = time_to_batch_no(datetime.now())

    mongo = Mongo()
    bulk_list = list()
    parser = CatParser()
    data_list = parser.parse_catalog('../doc/cat_6.12.xlsx')
    if data_list:
        for data in data_list:
            data['batchNo'] = batch_no
            bulk_list.append(UpdateOne({'_id': data.pop("catalogId")}, {'$set': data}, upsert=True))
        mongo.db['cat_{}'.format(batch_no)].bulk_write(bulk_list, ordered=False, bypass_document_validation=True)
        mongo.db['catalog_pool'].bulk_write(bulk_list, ordered=False, bypass_document_validation=True)
